package guzb.cnblogs.security.industrydemo.auth.restful;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 前后端分离的“用户名密码”认证模式
 */
public class MyUsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    public MyUsernamePasswordAuthenticationFilter() {
        super("/api/auth/login");
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        MyUsernamePasswordAuthenticationToken myAuthTokenRequest = new MyUsernamePasswordAuthenticationToken(username, password);
        // 设置认证请求的客户端信息，如浏览器名称、IP地址等
        Object clientAgentDetails = this.authenticationDetailsSource.buildDetails(request);
        myAuthTokenRequest.setDetails(clientAgentDetails);

        return getAuthenticationManager().authenticate(myAuthTokenRequest);
    }
}
